﻿using System.Text;
using EmbeddedSharp.Core;
using System;

namespace Ascend.Runtime.Core
{
    public class AscendLexer : Lexer
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public AscendLexer(string source)
            : base(source)
        {
        }

        /// <summary>
        /// Skips a section of comment begins with (* and ends with *).
        /// </summary>
        protected override void SkipComments()
        {
            char chr = source[Index];
            var buffer = new StringBuilder();

            if (chr == '(')
            {
                char cxx = source[Index + 1];
                if (cxx == '*')
                {
                    Index++;
                    buffer.Append(chr).Append(cxx);
                    while (Index + 1 < source.Length)
                    {
                        cxx = source[++Index];
                        buffer.Append(cxx);
                        if (cxx == '*' && source[Index + 1] == ')')
                        {
                            cxx = source[++Index];
                            buffer.Append(cxx);
                            break;
                        }
                    }
                }

                LastComment = buffer.ToString();
            }
        }


        /// <summary>
        /// Returns the next number
        /// </summary>
        /// <returns></returns>
        public override Token ReadNumber()
        {
            char chr = source[Index];
            StringBuilder buffer = new StringBuilder();

            do
            {
                buffer.Append(chr);

                Index++;
                if (Index >= base.source.Length)
                {
                    break;
                }

                chr = base.source[Index];
                if (chr == 'E' || chr == 'e')
                {
                    buffer.Append(chr);
                    Index++;

                    if (Index >= this.source.Length)
                    {
                        break;
                    }

                    chr = this.source[Index];
                }
            }
            while (
                (Char.IsDigit(chr) || chr == '.')
                // || chr == 'E' || chr == '-' || chr == '+' || chr == 'e')
                && Index < this.source.Length
                );

            token.TokenType = TokenType.Number;
            token.Value = buffer.ToString();

            return token;
        }
    }
}